package controllers

import (
	response "dict-server/models"
	"dict-server/models/dto"
	"dict-server/services" // 引入服务包，使用其中的ExampleService接口
	"fmt"
	"log"
	"net/http"
	"strings"
)

// WordController 单词相关请求控制器
type WordController struct {
	exampleService services.ExampleService // 依赖接口，而非具体实现
}

// NewWordController 创建单词控制器实例
// 参数改为接口类型，支持任意实现了ExampleService的服务
func NewWordController(exampleService services.ExampleService) *WordController {
	return &WordController{
		exampleService: exampleService,
	}
}

// WordDetailHandler 处理单词详情查询请求
func (c *WordController) WordDetailHandler(w http.ResponseWriter, r *http.Request) {
	// 获取URL参数中的单词
	word := strings.TrimSpace(r.PathValue("english"))
	if word == "" {
		response.Error(w, http.StatusBadRequest, "单词不能为空")
		return
	}
	// 转为小写
	word = strings.ToLower(word)

	// 调用数据库服务查询单词是否存在
	dbWord, err := services.GetWord(word)
	if err != nil {
		response.Error(w, http.StatusInternalServerError, "查询单词失败")
		log.Printf("查询单词失败: %v", err)
		return
	}
	if dbWord == nil {
		response.Error(w, http.StatusNotFound, "单词不存在")
		return
	}

	// 配置SSE响应头
	w.Header().Set("Content-Type", "text/event-stream; charset=utf-8")
	w.Header().Set("Cache-Control", "no-cache")
	w.Header().Set("Connection", "keep-alive")
	w.Header().Set("Access-Control-Allow-Origin", "*")

	// 发送单词基本信息
	initialResp := dto.WordResponse{
		Word:  dbWord.Word,
		Trans: dbWord.Trans,
	}
	response.SSESuccess(w, initialResp)

	// 刷新响应
	if f, ok := w.(http.Flusher); ok {
		f.Flush()
	}

	// 创建例句和错误通道
	examplesChan := make(chan dto.Example, 5)
	errorChan := make(chan error, 1)

	// 调用接口方法获取例句（不依赖具体服务实现）
	go c.exampleService.GetExamples(word, examplesChan, errorChan)

	// 收集例句并流式返回
	var examples []dto.Example
	const maxExamples = 5
	for len(examples) < maxExamples {
		select {
		case example, ok := <-examplesChan:
			if !ok {
				// 通道关闭，返回已收集的例句
				finalResp := dto.WordResponse{
					Word:     dbWord.Word,
					Trans:    dbWord.Trans,
					Examples: examples,
				}
				response.SSESuccess(w, finalResp)
				fmt.Fprintf(w, "event: close\ndata: done\n\n")
				if f, ok := w.(http.Flusher); ok {
					f.Flush()
				}
				return
			}
			// 将新收集的加入至examples中
			examples = append(examples, example)
			resp := dto.WordResponse{
				Word:     dbWord.Word,
				Trans:    dbWord.Trans,
				Examples: examples,
			}
			response.SSESuccess(w, resp)
			if f, ok := w.(http.Flusher); ok {
				f.Flush()
			}

			if len(examples) == maxExamples {
				// 已收集足够例句，返回最终结果
				finalResp := dto.WordResponse{
					Word:     dbWord.Word,
					Trans:    dbWord.Trans,
					Examples: examples,
				}
				response.SSESuccess(w, finalResp)
				fmt.Fprintf(w, "event: close\ndata: done\n\n")
				if f, ok := w.(http.Flusher); ok {
					f.Flush()
				}
				return
			}

		case err := <-errorChan:
			// 处理错误
			resp := dto.WordResponse{
				Word:     dbWord.Word,
				Trans:    dbWord.Trans,
				Examples: examples,
				Error:    fmt.Sprintf("获取例句失败: %v", err),
			}
			// 错误返回
			response.SSEError(w, http.StatusInternalServerError, resp.Error)
			fmt.Fprintf(w, "event: close\ndata: error\n\n")
			if f, ok := w.(http.Flusher); ok {
				f.Flush()
			}
			return

		// 此时客户端断开连接
		case <-r.Context().Done():
			// 客户端断开连接
			log.Printf("客户端断开连接: %s", word)
			return
		}
	}
}
